﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;

/// <summary>
/// 对象操作句柄，句柄可以很多，但是操作的都是同一个对象
/// </summary>
public struct PoolObjHandle<T> : IEquatable<PoolObjHandle<T>> where T : PooledClassObject {

	/// <summary>
	/// 跟对象的seq同步，这样可以对比是不是同一个对象
	/// </summary>
	public uint _handleSeq;

	public T _handleObj;

	/// <summary>
	/// 取得对象的操作句柄
	/// </summary>
	/// <value>The handle.</value>
	public T handle
	{
		get
		{
			return this._handleObj;
		}
	}

	public PoolObjHandle(T obj)
	{
		if (obj != null && obj.usingSeq > 0u)
		{
			this._handleSeq = obj.usingSeq;
			this._handleObj = obj;
		}
		else
		{
			this._handleSeq = 0u;
			this._handleObj = null;
		}
	}

	/// <summary>
	/// 启用当前对象， 如果对象已经为null，那么启用失败
	/// </summary>
	public void Validate() {
		this._handleSeq = ((this._handleObj == null) ? 0u : this._handleObj.usingSeq);
	}

	/// <summary>
	/// 释放当前对象
	/// </summary>
	public void Release()
	{
		this._handleObj = null;
		this._handleSeq = 0u;
	}

	public bool Equals(PoolObjHandle<T> other) {
		return this == other;
	}

	//重载操作符
	public static bool operator ==(PoolObjHandle<T> lhs, PoolObjHandle<T> rhs)
	{
		return lhs._handleObj == rhs._handleObj && lhs._handleSeq == rhs._handleSeq;
	}

	public static bool operator !=(PoolObjHandle<T> lhs, PoolObjHandle<T> rhs)
	{
		return lhs._handleObj != rhs._handleObj || lhs._handleSeq != rhs._handleSeq;
	}

	public override bool Equals(object obj)
	{
		return obj != null && base.GetType() == obj.GetType() && this == (PoolObjHandle<T>)obj;
	}

	public override int GetHashCode()
	{
		return base.GetHashCode();
	}

	//当前对象是否为true或者false
	public static implicit operator bool(PoolObjHandle<T> ptr)
	{
		return ptr._handleObj != null && ptr._handleObj.usingSeq == ptr._handleSeq;
	}

	/// 可以直接赋值给T
	public static implicit operator T(PoolObjHandle<T> ptr)
	{
		//implicit：表示隐式转换，如从 B -> A 只需直接赋值（A = B）  
		//explicti：表示显式转换，如从 A -> B 必须进行强制类型转换（B = (B)A） 
		return ptr.handle;
	}
}
